#include <fstream>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using namespace std;

struct state
{
    int          _state;
	int          _zpos;
	
	state(): 
	_state(0), 
	_zpos(-1)
	{}
};

void readState(const string& filename, state& outState)
{
	ifstream ifile(filename.c_str(), ifstream::in);
	int cur;
	outState._state = 0; 
	outState._zpos = -1;

	int i = 8;
	while (ifile >> cur)
	{
		outState._state *= 10;
		outState._state += cur; 
		if (cur == 0)
			outState._zpos = i;
		i--;
	}
	ifile.close();
}

int mypow (int n)
{
	int res = 1; 
	while (n--)
	{
		res *= 10; 
	}
	return res;
}

vector<state> getNeigh(const state & i)
{
	// up 
	vector<state> res; 

	if (i._zpos / 3 != 2) 
	{
		// up
		state cur = i; 
		int curvalue = cur._state / mypow(cur._zpos + 3) %10;
		cur._state += curvalue * mypow(cur._zpos) - curvalue * mypow(cur._zpos + 3);
		cur._zpos += 3; 
		res.push_back(cur);
	}
	if (i._zpos / 3 != 0)
	{
		// down 
		state cur = i; 
		int curvalue = cur._state / mypow(cur._zpos - 3) % 10; 
		cur._state += curvalue * mypow(cur._zpos) - curvalue * mypow(cur._zpos - 3);
		cur._zpos -= 3; 
		res.push_back(cur);
	}
	if (i._zpos % 3 != 2)
	{
		state cur = i; 
		int curvalue = cur._state / mypow(cur._zpos + 1) % 10; 
		cur._state += curvalue * mypow(cur._zpos) - curvalue * mypow(cur._zpos + 1);
		cur._zpos += 1; 
		res.push_back(cur);
	}
	if (i._zpos % 3 != 0)
	{
		state cur = i; 
		int curvalue = cur._state / mypow(cur._zpos - 1) % 10; 
		cur._state += curvalue * mypow(cur._zpos) - curvalue * mypow(cur._zpos - 1);
		cur._zpos -= 1; 
		res.push_back(cur);
	}
	return res;
}

int solve()
{
	state s, d; 
	readState("start1.txt", s);
	readState("goal.txt", d);
	vector<bool> reached(1000000000, false);

	int allRes = 0; 
	queue<state> q;
	q.push(s);
        reached[s._state] = true;
	allRes++;

	int distance = 0;
	while (!q.empty())
	{
		distance ++;
		queue<state> newq;

		while (!q.empty())
		{
			state cur = q.front();
			q.pop();

			vector<state> curneigh = getNeigh(cur);
			for (int i = 0; i < curneigh.size(); ++i)
			{
				if (!reached[curneigh[i]._state])
				{
					reached[curneigh[i]._state] = true;
					//if (curneigh[i]._state == d._state) return distance;

					newq.push(curneigh[i]);
                                        allRes++;
				}
			}
		}
		swap(q, newq);
	}
	cout << allRes << endl; 
	return -1;
}

int main()
{
	cout << solve() << endl; 
}